<template>
  <div class="bg-gray-50 py-8">
    <div class="max-w-7xl mx-auto px-4">
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 左侧用户卡片 -->
        <div class="lg:col-span-1">
          <div class="rounded-lg p-6 text-white shadow-lg" style="background-color: #0066a1;">
            <!-- 用户头像和信息 -->
            <div class="flex items-center mb-6">
              <div class="w-16 h-16 rounded-full mr-4 flex items-center justify-center text-white text-xl font-medium flex-shrink-0" 
                   style="background: linear-gradient(135deg, #5DADE2 0%, #48C9B0 100%);">
                {{ avatarText }}
              </div>
              <div class="flex-1 min-w-0">
                <h3 class="text-xl font-semibold truncate" :title="personalInfo.fullName">{{ personalInfo.fullName }}</h3>
                <p class="text-blue-200">Corporate Members</p>
              </div>
            </div>
            
            <!-- 菜单选项 -->
            <div class="space-y-3">
              <button  class="cursor-pointer"
                @click="activeTab = 'personal'"
                :class="[
                  'w-full text-left px-4 py-3 rounded-md border-2 border-white flex items-center justify-between transition-colors',
                  activeTab === 'personal' ? 'bg-white' : 'bg-transparent text-white hover:bg-blue-500'
                ]"
                :style="activeTab === 'personal' ? 'color: #0066a1;' : ''"
              >
                <span>Personal Information</span>
                <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </button>
              
              <button   class="cursor-pointer"
                @click="activeTab = 'declaration'"
                :class="[
                  'w-full text-left px-4 py-3 rounded-md border-2 border-white flex items-center justify-between transition-colors',
                  activeTab === 'declaration' ? 'bg-white' : 'bg-transparent text-white hover:bg-blue-500'
                ]"
                :style="activeTab === 'declaration' ? 'color: #0066a1;' : ''"
              >
                <span>Declaration record</span>
                <svg class="w-5 h-5" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M17 8l4 4m0 0l-4 4m4-4H3" />
                </svg>
              </button>
            </div>
          </div>
        </div>
        
        <!-- 右侧内容区域 -->
        <div class="lg:col-span-2">
          <!-- Personal Information Tab -->
          <div v-if="activeTab === 'personal'" class="bg-white rounded-lg p-8 shadow-lg">
            <h2 class="text-3xl font-bold mb-8" style="color: #0066a1;">Personal Information</h2>
            
            <form @submit.prevent="savePersonalInfo" class="space-y-6">
              <!-- 第一行：姓名和职位 -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-medium mb-2" style="color: #0066a1;">Full Name</label>
                  <input 
                    v-model="personalInfo.fullName"
                    type="text" 
                    class="w-full px-4 py-3 bg-gray-100 border-0 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="manager zhang"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium mb-2" style="color: #0066a1;">Position</label>
                  <input 
                    v-model="personalInfo.position"
                    type="text" 
                    class="w-full px-4 py-3 bg-gray-100 border-0 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="green manager"
                  />
                </div>
              </div>
              
              <!-- 第二行：邮箱和电话 -->
              <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label class="block text-sm font-medium mb-2" style="color: #0066a1;">Email</label>
                  <input 
                    v-model="personalInfo.email"
                    type="email" 
                    class="w-full px-4 py-3 bg-gray-100 border-0 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Please enter the content"
                  />
                </div>
                <div>
                  <label class="block text-sm font-medium mb-2" style="color: #0066a1;">Cell-phone Number</label>
                  <input 
                    v-model="personalInfo.phone"
                    type="tel" 
                    class="w-full px-4 py-3 bg-gray-100 border-0 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                    placeholder="Please enter the content"
                  />
                </div>
              </div>
              
              <!-- 第三行：公司名称 -->
              <div>
                <label class="block text-sm font-medium mb-2" style="color: #0066a1;">Corporate Name</label>
                <input 
                  v-model="personalInfo.companyName"
                  type="text" 
                  class="w-full px-4 py-3 bg-gray-100 border-0 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="Please enter the content"
                />
              </div>
              
              <!-- 第四行：公司地址 -->
              <div>
                <label class="block text-sm font-medium mb-2" style="color: #0066a1;">Company Address</label>
                <textarea 
                  v-model="personalInfo.companyAddress"
                  rows="3"
                  class="w-full px-4 py-3 bg-gray-100 border-0 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder="Please enter the content"
                ></textarea>
              </div>
              
              <!-- 保存按钮 -->
              <div class="pt-4">
                <button 
                  type="submit"
                  class="text-white px-8 cursor-pointer py-3 rounded-md transition-colors font-medium"
                  style="background-color: #0066a1;"
                >
                  Save modifications
                </button>
              </div>
            </form>
          </div>
          
          <!-- Declaration record Tab -->
          <div v-if="activeTab === 'declaration'" class="bg-white rounded-lg p-8 shadow-lg">
            <!-- Header -->
            <div class="flex justify-between items-center mb-6">
              <h2 class="text-3xl font-bold " style="color: #0066a1;">Declaration record</h2>
              <button @click="navigateTo('/echart/listIndustry')" class="cursor-pointer flex items-center text-white px-4 py-2 rounded-md" style="background-color: #0066a1;">
                <svg class="w-5 h-5 mr-2" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" d="M12 4v16m8-8H4" />
                </svg>
                New declaration
              </button>
            </div>
            
            <!-- Table -->
            <div class="overflow-x-auto">
              <table class="w-full text-left text-gray-700">
                <thead class="text-gray-800">
                  <tr class="border border-gray-300 rounded-t-lg bg-gray-50">
                    <th class="p-3 font-semibold">Id</th>
                    <th class="p-3 font-semibold">Industry</th>
                    <th class="p-3 font-semibold">Declaration time</th>
                    <th class="p-3 font-semibold">state</th>
                    <th class="p-3 font-semibold">operate</th>
                  </tr>
                </thead>
                <tbody>
                  <tr v-for="record in declarationRecords" :key="record.id" style="border-bottom: 1px solid #eee;" class="border-b hover:bg-blue-50 transition-colors">
                    <td class="p-3">{{ record.id }}</td>
                    <td class="p-3">{{ record.industry }}</td>
                    <td class="p-3">{{ record.declarationTime }}</td>
                    <td class="p-3">
                      <span :class="[
                        'px-3 py-1 text-sm rounded-full',
                        record.state === 'Success' ? 'bg-green-100 text-green-700' : 
                        record.state === 'In Progress' ? 'bg-yellow-100 text-yellow-700' : 'bg-red-100 text-red-700'
                      ]">
                        {{ record.state }}
                      </span>
                    </td>
                    <td class="p-3">
                      <a @click="openDetails(record.id)" class="text-blue-600 hover:underline cursor-pointer" style="color: #0066a1;">View details</a>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>

            <!-- Pagination -->
            <div class="flex justify-between items-center mt-6 text-sm text-gray-600">
              <span>Display 1 to {{ Math.min(pageSize, total) }} of a total of {{ total }} records</span>
              <div class="flex items-center space-x-1">
                <button 
                  @click="handlePageChange(pageNum - 1)" 
                  :disabled="pageNum <= 1"
                  class="p-2 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  ‹
                </button>
                <button 
                  v-for="page in Math.ceil(total / pageSize)" 
                  :key="page"
                  @click="handlePageChange(page)"
                  :class="[
                    'px-3 py-1 rounded',
                    page === pageNum ? 'bg-blue-100 text-blue-600' : 'text-gray-600 hover:bg-gray-100'
                  ]"
                >
                  {{ page }}
                </button>
                <button 
                  @click="handlePageChange(pageNum + 1)" 
                  :disabled="pageNum >= Math.ceil(total / pageSize)"
                  class="p-2 text-gray-400 hover:text-gray-600 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  ›
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { userApi } from '~/public/utils/api'

const activeTab = ref('personal')
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

const personalInfo = ref({
  fullName: '',
  position: '',
  email: '',
  phone: '',
  companyName: '',
  companyAddress: ''
})

// 计算头像显示文字
const avatarText = computed(() => {
  const name = personalInfo.value.fullName || 'U'
  
  // 检测是否包含中文字符
  const hasChinese = /[\u4e00-\u9fa5]/.test(name)
  
  if (hasChinese) {
    // 中文名字：取后两个字符
    return name.length >= 2 ? name.slice(-2) : name
  } else {
    // 英文名字：取最后一个单词（lastName）的首字母，大写
    const words = name.trim().split(/\s+/)
    const lastName = words[words.length - 1]
    return lastName ? lastName.charAt(0).toUpperCase() : 'U'
  }
})

const declarationRecords = ref([])

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const result = await userApi.getUserInfo()
    if (result.data) {
      personalInfo.value = {
        fullName: result.data.fullName || personalInfo.value.fullName,
        position: result.data.position || personalInfo.value.position,
        email: result.data.email || '',
        phone: result.data.phone || '',
        companyName: result.data.companyName || '',
        companyAddress: result.data.companyAddress || ''
      }
      console.log('User info:', result.data) // 调试用
    }
  } catch (error) {
    console.error('Failed to fetch user info:', error)
  }
}

const savePersonalInfo = async () => {
  try {
    const result = await userApi.updateUserInfo({
      fullName: personalInfo.value.fullName,
      position: personalInfo.value.position,
      email: personalInfo.value.email,
      phone: personalInfo.value.phone,
      companyName: personalInfo.value.companyName,
      companyAddress: personalInfo.value.companyAddress
    })
    
    if (result.code === 200) {
      // 同步更新 auth 中的用户信息
      const { $auth } = useNuxtApp()
      $auth.updateUser({
        fullName: personalInfo.value.fullName,
        email: personalInfo.value.email,
        position: personalInfo.value.position,
        phone: personalInfo.value.phone,
        companyName: personalInfo.value.companyName,
        companyAddress: personalInfo.value.companyAddress
      })
      
      const { $toast } = useNuxtApp()
      $toast.success('Personal information saved successfully')
    }
  } catch (error) {
    console.error('Failed to save personal info:', error)
    const { $toast } = useNuxtApp()
    $toast.error('Failed to save personal information')
  }
}

// 获取申报记录
const fetchDeclarationRecords = async () => {
  try {
    const result = await userApi.getRecordsList({ pageSize: pageSize.value, pageNum: pageNum.value })
    if (result.code === 200) {
      total.value = result.total || 0
      declarationRecords.value = (result.rows || []).map(record => ({
        id: record.recordId,
        industry: record.industryName,
        declarationTime: record.createTime,
        state: record.state === 1 ? 'In Progress' : record.state === 2 ? 'Success' : 'Failed'
      }))
    }
  } catch (error) {
    console.error('Failed to fetch declaration records:', error)
  }
}

// 分页处理
const handlePageChange = (page) => {
  pageNum.value = page
  fetchDeclarationRecords()
}

// 打开详情页面
const openDetails = (recordId) => {
  if (process.client) {
    window.open(`/echart?recordId=${recordId}`, '_blank')
  }
}

onMounted(async () => {
  await Promise.all([
    fetchUserInfo(),
    fetchDeclarationRecords()
  ])
})

// 设置页面标题
useHead({
  title: 'User Center - Carbon Tariff Platform',
  meta: [
    { name: 'description', content: 'Manage your carbon accounting records, view declaration history, and access personalized carbon tariff services' },
    { name: 'keywords', content: 'user dashboard, carbon accounting records, declaration management, personal center' }
  ]
})
</script>
